<?php

namespace App\Kuafu\WaiMai\Service;

use App\Kuafu\Mqtt\Enum\MqttCodeEnum;
use App\Kuafu\Mqtt\Service\MqttService;
use App\Kuafu\Mybank\Service\MybankBrokerageService;
use App\Kuafu\Mybank\Service\MybankCalcWaimaiBrokerageService;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\WaiMai\Channel\BaseWaiMai;
use App\Kuafu\WaiMai\Enum\MtWaiMaiEnum;
use App\Kuafu\WaiMai\Enum\WaiMaiCodeEnum;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Exceptions\WaiMaiException;
use App\Kuafu\WaiMai\Model\WaiMaiOrderDetailModel;
use App\Kuafu\WaiMai\Model\WaiMaiOrderIdShopIdMappingModel;
use App\Kuafu\WaiMai\Model\WaiMaiOrderModel;
use App\Kuafu\WaiMai\Model\WaiMaiShopMappingModel;
use App\Library\SnowFlake\SnowFlake;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class MtWaiMaiOrderService extends BaseWaiMaiOrderService
{
    private ?int             $orderId;
    private WaiMaiOrderModel $waiMaiOrder;
    private string           $thirdShopId;
    private int              $shopId;
    private int              $orderStatus;

    public function init(): self
    {
        $this->requestData = $this->recDecode($this->requestData);
        $this->orderId     = (int)($this->requestData['order_id'] ?? 0);
        if (config('app.pressure')) {
            $this->orderId = SnowFlake::nextIdCache();
        }

        $this->thirdShopId = (string)($this->requestData['wm_poi_id'] ?? '');

        if ($this->thirdShopId) {

            // 转换shopId
            $this->shopId = WaiMaiShopMappingModel::getShopIdByThirdShopId($this->thirdShopId,
                CodeEnum::SOURCE_TYPE_MT);
            if (!$this->shopId) {
                BaseWaiMaiOrderService::$errMsg = WaiMaiCodeEnum::CODE_TEXT[WaiMaiCodeEnum::ERR_MT_EMPTY_SHOP_MAPPING];
            }
        } else {

            // 实际试下来，这个接口的shopId需要手动查
            $this->shopId = WaiMaiOrderIdShopIdMappingModel::getShopId($this->orderId);
        }

        $this->waiMaiOrder = new WaiMaiOrderModel(['orderId' => $this->orderId, 'shopId' => $this->shopId]);

        $this->orderStatus = (int)WaiMaiOrderModel::suffix($this->shopId)
                                                  ->where('orderId', $this->orderId)
                                                  ->value('orderStatus') ?? 0;

        return $this;
    }

    // 递归解析requestData
    public function recDecode(array $arr)
    {
        foreach ($arr as &$v) {
            if (is_string($v)) {
                $v = urldecode($v);

                if (isset($v[0]) && (($v[0] == '[') || ($v[0] == '{'))) {
                    $v = json_decode($v, true);
                    if ($v == null) {
                        continue;
                    }
                    $v = $this->recDecode($v);
                }
            }
        }

        return $arr;
    }

    /**
     * 创建美团订单
     * 接口文档：https://developer.waimai.meituan.com/home/docDetail/172
     */
    public function createOrder()
    {
        if (!$this->shopId) {
            return false;
        }

        // 针对每个订单加锁
        $this->lockFuncBefore($this->orderId, __FUNCTION__);

        // 转换shopId
        $data['shopId'] = $this->shopId;

        // 判断订单是否存在
        $order = WaiMaiOrderModel::suffix($this->shopId)->where('orderId', $this->orderId)->first();
        if ($order) {

            // 没接单的话，要接单
            if ($order->orderStatus == WaiMaiDBEnum::ORDER_STATUS_1) {

                // 自动接单
                BaseWaiMai::getIns($this->sourceType, $data['shopId'])->acceptOrder($this->orderId);
            }

            // 存在的直接忽略
            BaseWaiMaiOrderService::$errMsg = '订单已存在';

            $this->lockFuncAfter($this->orderId, __FUNCTION__);

            return true;
        }

        // 订单降级
        if (isset($this->requestData['incmp_code']) && $this->requestData['incmp_code'] == MtWaiMaiEnum::INCMP_CODE_ERROR) {
            Log::info("WAIMAI ORDER DEMOTION...shopId:{$this->shopId} orderId:{$this->orderId}");

            // 调用订单详情 - 重新获取
            $apiData = BaseWaiMai::getIns($this->sourceType, $this->shopId)->getOrderDetail($this->orderId)['oriData'] ?? [];
            $this->requestData = $this->recDecode(is_array($apiData) ? $apiData : []);
        }

        // 商品详情
        $packingPriceOri = 0;
        foreach ($this->requestData['detail'] ?? [] as $detail) {
            $packingPriceOri += ((float)bcmul($detail['box_price'], $detail['box_num'], 2));
        }

        $data['brandId'] = ShopService::getShopInfo($data['shopId'])->brandId ?? 0;

        $data['orderId']       = $this->orderId;
        $orderCreatedAt        = $data['createdAt'] = $data['updatedAt'] = $this->requestData['ctime'] ?? time();
        $data['sourceType']    = $this->sourceType;
        $data['serialNum']     = $this->requestData['day_seq'] ?? 0;
        $data['originalPrice'] = $this->bcmul100($this->requestData['original_price'] ?? 0);
        $data['payPrice']      = $this->bcmul100($this->requestData['total'] ?? 0);
        $data['shippingPrice'] = $data['originalShippingPrice'] = $this->bcmul100($this->requestData['shipping_fee'] ?? 0);

        // 优惠的配送费
        $discountShippingPrice = $this->bcmul100(collect($this->requestData['extras'] ?? [])
            ->whereIn('type', [16, 21, 25, 30, 36, 48, 54])->sum('reduce_fee'));
        $data['shippingPrice'] -= $discountShippingPrice;


        $data['packingPrice'] = $this->bcmul100($packingPriceOri);
        $data['orderStatus']  = $orderStatus = self::convertOrderStatus($this->requestData['status'] ?? MtWaiMaiEnum::ORDER_STATUS_8);
        $data['completeTime'] = $orderStatus == WaiMaiDBEnum::ORDER_STATUS_5 ? ($this->requestData['order_completed_time'] ?? 0) : 0;
        $data['acceptTime']   = $this->requestData['order_confirm_time'] ?? 0;
        $data['remark']       = $this->requestData['caution'] ?? '';

        $p_detail                = $this->requestData['poi_receive_detail'] ?? [];
        $data['platformPrice']   = $p_detail['foodShareFeeChargeByPoi'] ?? 0;
        $data['expectIncome']    = $p_detail['wmPoiReceiveCent'] ?? 0;

        $delivery_time = $this->requestData['delivery_time'] ?? "0";
        $data['expectFast']      = $delivery_time == "0" ? 1 : 0;
        $data['expectTime']      = $this->requestData['estimate_arrival_time'] ?? 0;
        $data['senderName']      = '';
        $data['senderPhone']     = '';
        $data['receiverName']    = $this->requestData['recipient_name'] ?? '';
        $data['receiverPhone']   = $this->requestData['recipient_phone'] ?? '';
        $data['receiverAddress'] = $this->requestData['recipient_address'] ?? '';

        $data['redPrice']           = $this->bcmul100(collect($this->requestData['extras'] ?? [])
//            ->where('type', 9)
            ->sum('reduce_fee'));
        $data['redLists']           = json_encode(collect($this->requestData['extras'] ?? [])
//            ->where('type', 9)
            ->reject(function ($item) {
                if (!$item) {
                    return true;
                }
            })->values()
            ->map(function ($item) {
                return [
                    'n' => $item['remark'] ?? '',
                    'p' => $this->bcmul100($item['reduce_fee']),
                ];
            })->values()->toArray(), JSON_UNESCAPED_UNICODE);
        $data['fullReductionPrice'] = $this->bcmul100(collect($this->requestData['extras'] ?? [])
            ->where('type', 2)
            ->sum('reduce_fee'));

        $data['receiverPrivacyPhones'] = json_encode($this->requestData['backup_recipient_phone'] ?? []);

        // 商家活动承担金额
        $data['activityExpenditure'] = (int)collect($p_detail['actOrderChargeByPoi'] ?? [])->sum('moneyCent');

        // 优惠金额 = 菜品原价合计 + 包装费 - 营业收入
        $data['discountPrice'] = $data['originalPrice'] - $data['originalShippingPrice'] - $data['expectIncome'];

        // 其他支出 = 菜品原价合计 + 包装费 - 营业收入 - 平台服务费 - 商家活动支出
        $data['otherPrice'] = $data['discountPrice'] - $data['platformPrice'] - $data['activityExpenditure'];

        // 开票信息
        if (isset($this->requestData['has_invoiced']) && $this->requestData['has_invoiced']) {
            $data['taxpayers'] = json_encode([
                WaiMaiDBEnum::TAX_CODE  => $this->requestData['taxpayer_id'] ?? '',
                WaiMaiDBEnum::TAX_TITLE => $this->requestData['invoice_title'] ?? '',
            ], JSON_UNESCAPED_UNICODE);
        } else {
            $data['taxpayers'] = "[]";
        }

        DB::connection('mysqlWaiMai')->beginTransaction();

        $this->waiMaiOrder->addData($data);

        // orderId -> shopId 映射表
        WaiMaiOrderIdShopIdMappingModel::addData($this->orderId, $this->shopId, $this->sourceType);

        $orderDetailData = [];
        foreach ($this->requestData['detail'] ?? [] as $detail) {
            $num = $detail['quantity'] ?? 0;

            $orderDetailData[] = [
                'brandId'           => ShopService::getShopInfo($this->shopId)->brandId ?? 0,
                'shopId'            => $this->shopId,
                'orderId'           => $this->orderId,
                'productName'       => $productName = $detail['food_name'] ?? '',
                'productNameStandard' => preg_replace('/\[[^\]]*\]$/', '', $productName),
                'unit'              => $detail['unit'] ?? '',
                'num'               => $num,
                'originalUnitPrice' => $originalUnitPrice = $this->bcmul100($detail['price'] ?? 0),
                'originalPrice'     => $originalUnitPrice * $num,
                'productProperty'   => $detail['food_property'] ?? '',
                'createdAt'         => $orderCreatedAt,
                'updatedAt'         => $orderCreatedAt,
                'productType'       => WaiMaiOrderDetailModel::PRODUCT_TYPE_1,
                'sourceType'        => $this->sourceType,
                'pocketId'          => ($detail['cart_id'] ?? 0) + 1,
                'uniqueId'          => '',
                'skuId'             => $detail['mt_sku_id'] ?? '',
            ];
        }

        // 菜品明细加上包装物
        $this->pushPacking($orderDetailData, $data['packingPrice']);

        // 平台菜的优惠
        $this->shareDetailDiscount($orderDetailData, $data['discountPrice']);

        // 平摊菜品实收
        $this->shareDetailIncomes($orderDetailData, $data['expectIncome']);

        // 添加赠品
        collect($this->requestData['extras'] ?? [])
            ->where('type', 5)
            ->each(function ($item) use (&$orderDetailData) {
                if (isset($item['act_extend_msg'])) {
                    $this->addGift($orderDetailData, $item['act_extend_msg']['gifts_name'] ?? '', $item['act_extend_msg']['gift_num'] ?? 0);
                }
            });

        WaiMaiOrderDetailModel::addData($orderDetailData);

        DB::connection('mysqlWaiMai')->commit();

        if (!config('app.pressure')) {

            // 自动接单
            $accept = BaseWaiMai::getIns($this->sourceType, $data['shopId'])->acceptOrder($this->orderId);

            try {
                if (!$accept['status'] && ($accept['data']['hasConfirm'] ?? 0) == 1 && $orderStatus < WaiMaiDBEnum::ORDER_STATUS_5) {

                    Log::info("pushOrder accept in :{$this->orderId}", $accept);

                    // 已经确认了-直接调用接单
                    $this->orderStatus = $orderStatus;
                    $this->acceptOrder();
                }
            } catch (\Exception $e) {
                Log::warning("pushOrder accept err:" . $e->getMessage());
                Log::warning($e);
            }
        }

        // 自动出餐相关操作
        $this->autoFinish($data);

        $this->lockFuncAfter($this->orderId, __FUNCTION__);

        return true;
    }

    // 接单
    public function acceptOrder(): bool
    {
        if (!$this->shopId) {
            return true;
        }

        // 已完成、取消
        if (in_array($this->orderStatus, WaiMaiDBEnum::ORDER_STATUS_OVER)) {
            BaseWaiMaiOrderService::$errMsg = '订单状态已完结';
            return true;
        }

        $db = WaiMaiOrderModel::suffix($this->shopId)->where('orderId', $this->orderId)->count();
        if (!$db) {

            $repair = $this->repairOrder($this->shopId, $this->orderId);
            if (!$repair) {
                return false;
            }
        }

        $updateTime = (int)($this->requestData['utime'] ?? 0);
        $this->waiMaiOrder->acceptOrder($updateTime);

        WaiMaiMqttService::getIns($this->shopId)
                         ->takeOutOrderOperate($this->sourceType, $this->orderId, MqttCodeEnum::TAKE_OUT_OPERATE_TYPE_2);

        return true;
    }

    // 订单取消 = 取消 + 全额退款
    public function cancelOrder(): bool
    {
        if (!$this->shopId) {
            return true;
        }

        // 已取消
        if ($this->orderStatus == WaiMaiDBEnum::ORDER_STATUS_7) {
            BaseWaiMaiOrderService::$errMsg = '订单状态已取消';
            return true;
        }

        $reason = $this->requestData['reason'] ?? '';

        $this->waiMaiOrder->cancelOrderFinish();

        $this->finishHook();

        // MQTT
        (new MqttService(0, $this->shopId))->takeOutOrder($this->orderId, WaiMaiDBEnum::SOURCE_TYPE_MT_WM,
            MqttCodeEnum::TAKE_OUT_OPERATE_TYPE_5, [
                'needConfirm' => false,
            ]);

        return true;
    }

    // 全额退款
    public function refundTotalOrder()
    {
        if (!$this->shopId) {
            return true;
        }

        // 已取消
        if ($this->orderStatus == WaiMaiDBEnum::ORDER_STATUS_7) {
            BaseWaiMaiOrderService::$errMsg = '订单状态已取消';
            return true;
        }

        $reason = $this->requestData['reason'] ?? '';

        // 通知类型：apply：发起退款；agree：确认退款；reject：驳回退款；cancelRefund：用户取消退款申请
        $notifyType = $this->requestData['notify_type'] ?? '';
        $pictures   = json_encode($this->requestData['pictures'] ?? '');

        // 实际试下来，这个接口的shopId需要手动查
        $this->shopId = WaiMaiOrderIdShopIdMappingModel::getShopId($this->orderId);

        // 退款金额
        //（注：
        //消息类型msg_type：
        //1:全部退款申请
        //2:全部退款申请处理(同意or拒绝)
        //3:全部退款退款成
        //4:全部退款失败
        //11:部分退款申请
        //12:部分退款申请处理(同意or拒绝)
        //13:部分退款退款成功
        //14:部分款退款失败
        // 23:重复支付退款）
        //当 msg_type > 10时，有金额money退款字段
        $money = $this->requestData['money'] ?? '';

        // 0：未处理；1：商家驳回退款请求；2、商家同意退款；3、客服驳回退款请求；4、客服帮商家同意退款；5、超过3小时自动同意；6、系统自动确认；7：用户取消退款申请；8：用户取消退款申诉
        $resType = $this->requestData['res_type'] ?? 0;

        // 同意退款 - 需要处理一下，其他的不用管
        if ($notifyType == MtWaiMaiEnum::NOTIFY_TYPE_AGREE) {

            $this->waiMaiOrder->cancelOrderFinish();

            // 把菜品的部分退款清空
            WaiMaiOrderDetailModel::clearPartRefundNum($this->shopId, $this->orderId);

            // MQTT
            (new MqttService(0, $this->shopId))->takeOutOrder($this->orderId, WaiMaiDBEnum::SOURCE_TYPE_MT_WM,
                MqttCodeEnum::TAKE_OUT_OPERATE_TYPE_5, [
                    'needConfirm' => false,
                ]);

            $this->finishHook();

            return true;
        }

        // 当前的订单状态
        $orderStatus = BaseWaiMai::getIns($this->sourceType, $this->shopId)->getOrderDetail($this->orderId)['data']['orderStatus'] ?? WaiMaiDBEnum::ORDER_STATUS_5;

        // 发起退款申请
        if ($notifyType == MtWaiMaiEnum::NOTIFY_TYPE_APPLY) {

            $this->waiMaiOrder->applyCancelOrder($orderStatus, (string)$reason, $pictures);

            // MQTT
            (new MqttService(0, $this->shopId))
                ->takeOutOrder($this->orderId, WaiMaiDBEnum::SOURCE_TYPE_MT_WM, MqttCodeEnum::TAKE_OUT_OPERATE_TYPE_5, [
                    'needConfirm' => true,
                ]);
            return true;
        }

        // 拒绝退款
        if ($notifyType == MtWaiMaiEnum::NOTIFY_TYPE_REJECT) {
            $this->waiMaiOrder->recallCancelOrder($orderStatus, $reason);

            $this->finishHook();

            return true;
        }

        // 用户撤回退款
        if ($notifyType == MtWaiMaiEnum::NOTIFY_TYPE_CANCEL_APPEAL || $notifyType == MtWaiMaiEnum::NOTIFY_TYPE_CANCEL_REFUND) {
            $this->waiMaiOrder->recallCancelOrder($orderStatus, $reason);

            $this->finishHook();

            return true;
        }

        return true;
    }

    // 部分退款
    public function refundPartOrder()
    {
        if (!$this->shopId) {
            return true;
        }

        $notifyType  = $this->requestData['notify_type'] ?? '';
        $reason      = $this->requestData['reason'] ?? '';
        $pictures    = json_encode($this->requestData['pictures'] ?? '');
        $foodArr = collect($this->requestData['food'] ?? [])->map(function ($item) {
            return [
                'name'          => $item['app_food_code'] ?? '',
                'skuId'         => (string)($item['mt_sku_id'] ?? ''),
                'refundNum'     => $item['count'] ?? 0,
                'boxPrice'      => $this->bcmul100($item['box_price'] ?? 0),
                'originalPrice' => $this->bcmul100($item['origin_food_price'] ?? 0) * ($item['count'] ?? 0),
                'refundPrice'   => $this->bcmul100($item['refund_price'] ?? 0) * ($item['count'] ?? 0),
            ];
        });
        $platformRefundPrice = $this->bcmul100($this->requestData['money'] ?? 0);
        $userRefundPrice     = $foodArr->sum('refundPrice');

        // 当前的订单状态
        $orderStatus = BaseWaiMai::getIns($this->sourceType, $this->shopId)->getOrderDetail($this->orderId)['data']['orderStatus'] ?? WaiMaiDBEnum::ORDER_STATUS_5;

        // 发起部分退款
        if ($notifyType == MtWaiMaiEnum::NOTIFY_TYPE_PART) {

            // waimai_orders
            $this->waiMaiOrder->applyCancelOrder($orderStatus, (string)$reason, $pictures, WaiMaiDBEnum::IS_PART_REFUND_1);
            return true;
        }

        $connectionName = WaiMaiOrderDetailModel::suffix($this->shopId)->getConnectionName();

        // 同意退款
        if ($notifyType == MtWaiMaiEnum::NOTIFY_TYPE_AGREE) {
            DB::connection($connectionName)->beginTransaction();

            $packingPrice = (int)$foodArr->sum('boxPrice');
            $originalPrice = (int)$foodArr->sum('originalPrice');

            $this->waiMaiOrder->partRefundFinish(true, $platformRefundPrice, $orderStatus, $userRefundPrice, $packingPrice, $originalPrice);
            WaiMaiOrderDetailModel::partRefund($this->shopId, $this->orderId, $foodArr, true);

            DB::connection($connectionName)->commit();

            return true;
        }

        // 拒绝退款
        if ($notifyType == MtWaiMaiEnum::NOTIFY_TYPE_REJECT) {
            DB::connection($connectionName)->beginTransaction();
            $this->waiMaiOrder->partRefundFinish(false, 0, $orderStatus);
            WaiMaiOrderDetailModel::partRefund($this->shopId, $this->orderId, $foodArr, false);
            DB::connection($connectionName)->commit();

            return true;
        }

        $this->finishHook();

        return true;
    }

    // 订单完成
    public function completeOrder()
    {
        if (!$this->shopId) {
            return true;
        }

        if ($this->orderStatus == WaiMaiDBEnum::ORDER_STATUS_5) {
            return true;
        }

        $db = WaiMaiOrderModel::suffix($this->shopId)->where('orderId', $this->orderId)->count();
        if (!$db) {

            $repair = $this->repairOrder($this->shopId, $this->orderId);
            if (!$repair) {
                return false;
            }
        }

        $completeTime = (int)($this->requestData['utime'] ?? 0);
        $this->waiMaiOrder->completeOrder($completeTime);
        self::rectifyExpectIncome($this->waiMaiOrder->first(), $this->requestData);

        $this->finishHook();

        // MQTT
        (new MqttService(0, $this->shopId))->takeOutOrder($this->orderId, WaiMaiDBEnum::SOURCE_TYPE_MT_WM,
            MqttCodeEnum::TAKE_OUT_OPERATE_TYPE_4, []);

        return true;
    }

    /**
     * 校正实收
     * @param WaiMaiOrderModel $waiMaiOrderModel
     * @param array $requestData
     */
    public static function rectifyExpectIncome(WaiMaiOrderModel $waiMaiOrderModel, array $requestData)
    {
        // 无部分退款时，试着更新实收、平台费
        if ($waiMaiOrderModel->isPartRefund == 0) {
            $p_detail            = $requestData['poi_receive_detail'] ?? [];
            $new_platformPrice   = $p_detail['foodShareFeeChargeByPoi'] ?? 0;
            if ($new_platformPrice > 0) {
                $waiMaiOrderModel->platformPrice = $new_platformPrice;
            }

            $new_expectIncome    = $p_detail['wmPoiReceiveCent'] ?? 0;
            if ($new_expectIncome > 0) {
                $waiMaiOrderModel->expectIncome = $new_expectIncome;
            }

            // 有改动就更新
            if ($waiMaiOrderModel->getDirty()) {
                $waiMaiOrderModel->changeExpectIncomeAffect(false);
                $waiMaiOrderModel->save();
            }
        }
    }

    // 配送中
    public function deliveringOrder()
    {
        if (!$this->shopId) {
            return true;
        }

        // 已完成、取消
        if (in_array($this->orderStatus, WaiMaiDBEnum::ORDER_STATUS_OVER)) {
            BaseWaiMaiOrderService::$errMsg = '订单状态已完结';
            return true;
        }

        $senderName      = $this->requestData['dispatcher_name'] ?? '';
        $sendPhone       = $this->requestData['dispatcher_mobile'] ?? '';
        $logisticsStatus = $this->requestData['logistics_status'] ?? '';

        // 配送中
        if ($logisticsStatus == MtWaiMaiEnum::LOGISTICS_STATUS_20) {

            $this->waiMaiOrder->deliveringOrder($senderName, $sendPhone);

            // MQTT
            (new MqttService(0, $this->shopId))->takeOutOrder($this->orderId, WaiMaiDBEnum::SOURCE_TYPE_MT_WM,
                MqttCodeEnum::TAKE_OUT_OPERATE_TYPE_3, []);
        }

        // 骑手送达 - 订单置为完成
        if ($logisticsStatus == MtWaiMaiEnum::LOGISTICS_STATUS_40) {
            $this->requestData['utime'] = $this->requestData['time'] ?? time();
            $this->completeOrder();
        }

        return true;
    }

    // 结算推送
    public function billOrder()
    {
        return true;
    }

    // 结束触发的钩子
    public function finishHook(): void
    {
        try {
            $this->waiMaiOrder->saveBrokerage();
        } catch (\Exception $e) {
            Log::warning($e);
        }


    }

    // 后期修复异常状态
    public function repairStatus()
    {
        $data['orderStatus']  = $orderStatus = self::convertOrderStatus($this->requestData['status']);
        $data['completeTime'] = $orderStatus == WaiMaiDBEnum::ORDER_STATUS_5 ? ($this->requestData['order_completed_time'] ?? 0) : 0;
        if ($data['orderStatus'] == WaiMaiDBEnum::ORDER_STATUS_7) {
            $data['refundPrice'] = $data['refundPriceToUser'] = $this->bcmul100($this->requestData['total'] ?? 0);
        }

        $this->waiMaiOrder->update($data);

        self::rectifyExpectIncome($this->waiMaiOrder->first(), $this->requestData);

        $this->finishHook();

        return true;
    }

    /**
     * 转换orderStatus
     * @param string $waiMaiOrderStatus
     * @return int
     */
    public static function convertOrderStatus(string $waiMaiOrderStatus): int
    {
        return [
            MtWaiMaiEnum::ORDER_STATUS_1 => WaiMaiDBEnum::ORDER_STATUS_0, // 未支付
            MtWaiMaiEnum::ORDER_STATUS_2 => WaiMaiDBEnum::ORDER_STATUS_1, // 已支付，向商家推送订单
            MtWaiMaiEnum::ORDER_STATUS_3 => WaiMaiDBEnum::ORDER_STATUS_1, // 商家已收到
            MtWaiMaiEnum::ORDER_STATUS_4 => WaiMaiDBEnum::ORDER_STATUS_2, // 商家已确认
            MtWaiMaiEnum::ORDER_STATUS_6 => WaiMaiDBEnum::ORDER_STATUS_4, // 订单配送中
            MtWaiMaiEnum::ORDER_STATUS_7 => WaiMaiDBEnum::ORDER_STATUS_5, // 订单已送达
            MtWaiMaiEnum::ORDER_STATUS_8 => WaiMaiDBEnum::ORDER_STATUS_5, // 订单已完成
            MtWaiMaiEnum::ORDER_STATUS_9 => WaiMaiDBEnum::ORDER_STATUS_7, // 订单已取消
        ][$waiMaiOrderStatus];
    }
}
